<template>
  <div id="promotion-coupon">
    <el-container style="overflow-x:hidden;overflow-y:hidden; height:100%;">
      <el-scrollbar
        style="width:100%;height:100%;white-space: nowrap;"
        @mousewheel.native="wheel"
        ref="roleRoll"
        class="roleRoll"
      >
        <el-header>
          <!-- 查询开始 -->
          <el-form
            :inline="true"
            :model="formInline"
            class="demo-form-inline"
            style="margin-top:20px;display: flex;flex-wrap: wrap;"
          >
            <el-form-item>
              <el-input
                v-model="formInline.title"
                placeholder="请选择优惠卷标题"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="formInline.type"
                placeholder="请选择优惠卷类型"
              >
                <el-option
                  v-for="item in optionsLevel"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="formInline.status"
                placeholder="请选择优惠卷状态"
              >
                <el-option
                  v-for="item in optionsStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="onSubmit()"
                icon="el-icon-search"
                clearable
                v-permission="'promote:coupon:query'"
                >查询</el-button
              >
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="handleEdit(1)"
                v-permission="'promote:coupon:create'"
                >添加</el-button
              >
              <el-button
                type="primary"
                icon="el-icon-download"
                clearable
                @click="exports()"
                >当前页导出</el-button
              >
            </el-form-item>
          </el-form>
          <!-- 查询结束 -->
        </el-header>

        <el-main>
          <el-table
            :data="tableData"
            style="width: 100%;overflow-x:auto"
            :default-sort="{ prop: 'date', order: 'descending' }"
            align="center border show-summary"
            border
          >
            <!-- 列表数据 -->
            <el-table-column prop="id" label="优惠券ID" sortable>
            </el-table-column>
            <el-table-column prop="title" label="优惠券名称"> </el-table-column>
            <el-table-column label="优惠券类型">
              <template slot-scope="scope">{{
                scope.row.type | type
              }}</template>
            </el-table-column>
            <el-table-column prop="description" label="介绍"> </el-table-column>
            <el-table-column prop="total" label="优惠券数量"> </el-table-column>
            <el-table-column prop="surplus" label="剩余数量"> </el-table-column>
            <el-table-column prop="limit" label="每人限领"> </el-table-column>
            <el-table-column prop="discount" label="满减金额">
              <template slot-scope="scope">{{
                scope.row.discount | discount
              }}</template>
            </el-table-column>
            <el-table-column prop="min" label="最低消费">
              <template slot-scope="scope">{{ scope.row.min | min }}</template>
            </el-table-column>
            <el-table-column label="状态">
              <template slot-scope="scope">
                <el-tag>
                  {{ scope.row.status | status(scope.row.gmtEnd) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="使用类目名称">
              <template slot-scope="scope">
                <el-tag>
                  {{ scope.row.categoryTitle | categoryTitle }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="categoryId" label="使用类目ID">
            </el-table-column>
            <el-table-column label="领劵相对时间">
              <template slot-scope="scope">{{
                scope.row.days | days
              }}</template>
            </el-table-column>
            <el-table-column label="领劵开始时间">
              <template slot-scope="scope">{{
                scope.row.gmtStart | formatDate
              }}</template>
            </el-table-column>
            <el-table-column label="领劵结束时间">
              <template slot-scope="scope">{{
                scope.row.gmtEnd | formatDate
              }}</template>
            </el-table-column>
            <el-table-column label="操作" width="300">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="statusStatus(scope.$index, scope.row)"
                  v-permission="'promote:coupon:update'"
                  >{{ scope.row.status == 1 ? "冻结" : "激活" }}</el-button
                >
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleEdit(2, scope.$index, scope.row)"
                  v-permission="'promote:coupon:update'"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                  v-permission="'promote:coupon:delete'"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-main>
        <el-footer>
          <!-- 底部页数 -->
          <paging :paging="paging" :onSubmit="onSubmit"></paging>
        </el-footer>
      </el-scrollbar>
      <!-- 滚动组件结束 -->
    </el-container>
    <!-- 主要内容结束 -->

    <el-dialog :title="title" :visible.sync="dialogFormVisible" center>
      <!-- 对话框表单 -->
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        style="width:85%"
      >
        <el-form-item label="优惠券名称" prop="title">
          <el-input v-model="ruleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="优惠卷类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择优惠卷类型">
            <el-option
              v-for="item in optionsLevel"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              <template></template>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="介绍" prop="description">
          <el-input v-model="ruleForm.description"></el-input>
        </el-form-item>
        <el-form-item label="优惠券数量" prop="total">
          <el-input v-model="ruleForm.total">
            <template slot="append">张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="每人限领" prop="limit">
          <el-input v-model="ruleForm.limit">
            <template slot="append">张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="满减金额" prop="discount">
          <el-input v-model="ruleForm.discount">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="最低消费" prop="min">
          <el-input v-model="ruleForm.min">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="优惠卷状态" prop="status">
          <el-select v-model="ruleForm.status" placeholder="请选择优惠卷状态">
            <el-option
              v-for="item in optionsStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="有效期" class="timevalue">
          <el-radio-group v-model="radiodays" @change="selecttimes" :disabled="disabled2">
            <el-radio-button label="领券相对天数"></el-radio-button>
            <el-radio-button label="指定绝对时间"></el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="" v-show="selecttime" prop="days">
          <el-input v-model="ruleForm.days" :disabled="disabled2">
            <template slot="append">天</template>
          </el-input>
        </el-form-item>
        <el-form-item label="" v-show="!selecttime" class="timevalue" prop="gmtStart" >
          <el-date-picker
            v-model="ruleForm.gmtStart"
            type="datetime"
            placeholder="选择日期时间"
            :disabled="disabled2"
          >
          </el-date-picker
          >至
          <el-date-picker
            v-model="ruleForm.gmtEnd"
            type="datetime"
            placeholder="选择日期时间"
            :disabled="disabled2"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="商品限制范围">
          <el-radio-group v-model="radioscope" @change="scopes" :disabled="disabled">
            <el-radio-button label="全场通用"></el-radio-button>
            <el-radio-button label="指定分类"></el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优惠类目" v-show="scope">
            <el-cascader
                ref="coupon"
                v-model="ruleForm.categoryId"
                :options="optionsCoupon"
                :props="{ checkStrictly: true }"
                :disabled="disabled"
                clearable>
            </el-cascader>
        </el-form-item>
       
        <el-form-item style="text-align: center;">
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确定</el-button
          >
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import coupon from "@/api/coupon";
import Paging from "../../components/Paging";
import TimeDate from "@/util/TimeDate";
export default {
  components: {
    Paging,
  },
  data() {
    var validateTitle = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("优惠券标题不能为空"));
      } else {
        callback();
      }
    };
    var validateType = (rule, value, callback) => {
      if (value === null || value[0] === null) {
        //第一次进入是value为null，之后都是value[0]为null
        callback(new Error("优惠券类型不能为空"));
      } else {
        callback();
      }
    };
    var validateStatus = (rule, value, callback) => {
      if (value === null || value[0] === null) {
        //第一次进入是value为null，之后都是value[0]为null
        callback(new Error("优惠券状态不能为空"));
      } else {
        callback();
      }
    };
    var validateTotal = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("优惠券总量不能为空"));
      } else {
        let reg = /^[1-9][0-9]{0,}$/;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入整数"));
        }
      }
    };
    var validateLimit = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("优惠券限领不能为空"));
      } else {
        let reg = /^[1-9][0-9]{0,}$/;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入整数"));
        }
      }
    };
    var validateDiscount = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("优惠券折扣金额不能为空"));
      } else {
        let reg = /^[1-9][0-9]{0,}$/;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入整数"));
        }
      }
    };
    var validateMin = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("优惠券限领不能为空"));
      } else {
        let reg = /^[1-9][0-9]{0,}$/;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入整数"));
        }
      }
    };
    return {
      radiodays: "领券相对天数", //单选按钮天数
      radioscope: "全场通用", //单选按钮范围
      optionsLevel: [
        //选项框
        {
          value: 1,
          label: "满减劵",
        },
        {
          value: "",
          label: "全部",
        },
      ],
      optionsStatus: [
        //选项框性别
        {
          value: 1,
          label: "正常",
        },
        {
          value: 0,
          label: "下架",
        },
        {
          value: -1,
          label: "已过期",
        },
        {
          value: "",
          label: "全部",
        },
      ],
      formInline: {
        //查询数据
        title: "", //优惠卷标题
        type: null, //优惠卷类型
        status: null, //优惠卷状态
      },
      ruleForm: {
        //表单数据
        title: "", //优惠卷标题
        type: 1, //优惠卷类型
        status: 1, //优惠卷状态
        description: "", //优惠卷描述
        limit: 0, //用户限制领取
        discount: 0, //优惠价格
        min: 0, //满足优惠的最低价格
        total: 0, //优惠卷总数
        categoryTitle:'',
        categoryId: "", //优惠类别id
        days: "", //优惠时长
        gmtStart: "", //优惠开始时间
        gmtEnd: "", //优惠结束时间
      },
      roledata: "", //选中的数据
      index: "", //选中的下标
      rules: {
        //表单验证
        title: [{ required: true, validator: validateTitle, trigger: "blur" }],
        type: [{ required: true, validator: validateType, trigger: "blur" }],
        total: [{ required: true, validator: validateTotal, trigger: "blur" }],
        limit: [{ required: true, validator: validateLimit, trigger: "blur" }],
        discount: [
          { required: true, validator: validateDiscount, trigger: "blur" },
        ],
        min: [{ required: true, validator: validateMin, trigger: "blur" }],
        status: [
          { required: true, validator: validateStatus, trigger: "blur" },
        ],
      },
      title: "创造", //对话框的名字
      optionsCoupon:"",//选项框商品
      selecttime: true, //选择时间的输入方法
      scope:false,//优惠类目隐藏显示
      dialogFormVisible: false, //对话框表单的隐藏显示
      disabled: false, //禁用
      disabled2: false, //禁用
      tableData: [], //后台全部列表数据
      defaultProps: {
        children: "children",
        label: "label",
      },
      status:"冻结",
      paging: {
        currentPage: 1, //出现的页数
        pagesize: 10, //    每页的数据
        total: 0, //总条数
      },
    };
  },
  created: function() {
    //一开始的渲染数据
    let that = this;
    that.onSubmit();
    coupon.categoryTree().then((res) =>{
      this.optionsCoupon =res.data.data
    })
  },
  filters: {
    formatDate: function(value) {
      //转换时间戳
       return value ? TimeDate.format(new Date(value), "yyyy-MM-dd-hh:mm:ss") : "无";
    },
    type: function(value) {
      switch (value) {
        case 1:
          value = "满减劵";
          break;
        default:
          value = "全部";
          break;
      }
      return value;
    },
    status: function(value,tiems) {
      let date = new Date().getTime();
      if (date >tiems) {
        value = "已过期";
      } else {
        switch (value) {
          case 0:
            value = "下架";
            break;
          case 1:
            value = "正常";
            break;
        }
      }
      return value;
    },
    days: function(value) {
      if (value == undefined) {
        value = "无";
      }
      return value;
    },
    categoryTitle: function(value) {
      if (value == undefined) {
        value = "全部类目";
      }
      return value;
    },
    discount: function(value) {
      return "减免" + value + "元";
    },
    min: function(value) {
      return "满" + value + "元可用";
    },
  },
  methods: {
    onSubmit() {
      //查询
      let that = this;
      let data = Object.assign({pageNo:that.paging.currentPage,limit:that.paging.pagesize}, that.formInline);
      console.log(data)
      coupon
        .couponInquire(
          //查询接口封装
            data
          )
        .then((res) => {
          console.log(res);
          that.tableData = res.data.data.items; //获取数据赋值
          that.paging.total = res.data.data.total; //总条数
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    handleEdit(digit, index, row) {
      //编辑和添加
      let that = this;
      this.dialogFormVisible = true;
      this.resetForm("ruleForm");
      if (digit == 1) {
        this.title = "创造";
        this.ruleForm.gmtEnd =''
        this.disabled =false
        this.disabled2 =false
      } else {
        setTimeout(function() {
          //防止重置时没有数据
          that.title = "编辑";
          that.index = index;
          that.disabled =true
          that.disabled2 =true
          that.roledata = row;
          for (const i in that.ruleForm) {
            that.ruleForm[i] = row[i];
          }
          console.log( that.ruleForm)
          if (that.ruleForm.days!=undefined) {
            that.radiodays= "领券相对天数"
            that.selecttime =true
          }else{
            that.radiodays= "指定绝对时间"
            that.selecttime =false
          }
          if (that.ruleForm.categoryId!=undefined) {
            that.radioscope= "指定分类"
            that.scope =true
          }else{
            that.radioscope= "全场通用"
            that.scope =false
          }
        }, 100);
      }
    },
    submitForm(formName) {
      //提交
      let that = this;
      console.log(this.ruleForm)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          if (that.title == "创造") {
            //添加
            that.addition();
          } else {
            //编辑
            that.compile();
          }
        } else {
          return false;
        }
      });
    },
    addition() {
      //添加
      if (this.scope) {
        this.ruleForm.categoryId =this.$refs.coupon.getCheckedNodes()[0].data.value
      }
      let that = this;
      coupon
        .couponAdd(
          //添加封装接口
          that.ruleForm
        )
        .then(function(res) {
          console.log(res)
          if (res.data.errmsg == "成功") {
            that.topTips(res.data.errmsg, "success");
            that.paging.total = that.paging.total + 1; //总共条数+1条
            that.onSubmit();
          that.tableData.unshift(res.data.data);
          } else {
            that.topTips(res.data.errmsg, "warning");
          }
        });
    },
    compile() {
      //编制
      let that = this;
       let data = Object.assign({id:that.roledata.id,surplus:that.roledata.surplus},that.ruleForm);
      coupon
        .couponUpdate(
          //编制封装接口
            data
        )
        .then(function(res) {
          console.log(res)
          if (res.data.errmsg == "成功") {
            that.topTips(res.data.errmsg, "success");
            for (let j in that.ruleForm) {
               that.tableData[that.index][j] = that.ruleForm[j];
             }
          } else {
            that.topTips(res.data.errmsg, "warning");
          }
        });
    },
    resetForm(formName) {
      //重置验证
      let that = this;
      setTimeout(function() {
        that.$refs[formName].resetFields();
      }, 100);
    },
    selecttimes() {
      this.selecttime = !this.selecttime;
    },
    scopes() {
      this.scope = !this.scope;
    },
    handleDelete(index, row) {
      //删除
      console.log(row);
      let that = this;
      this.$confirm("此操作将永久删除--" + row.title + "--, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          coupon
            .couponDelete({
              //删除封装接口
              id: row.id,
            })
            .then(function(res) {
              if (res.data.errmsg == "成功") {
                that.topTips(res.data.errmsg, "success");
                that.paging.total = that.paging.total - 1; //总共条数-1条
                that.tableData.splice(index, 1);
              } else {
                that.topTips(res.data.errmsg, "error");
              }
            });
        })
        .catch(() => {
          this.topTips("已取消删除", "info");
        });
    },
    statusStatus(index, row) {//状态
      console.log(index, row);
      let that = this;
      let status = row.status;
      if (status == 1) {
        //判断状态
        status = 0;
      } else {
        status = 1;
      }
      coupon
        .updateCouponStatus({
          id: row.id,
          status: status,
        })
        .then(function(res) {
          if (res.data.errmsg == "成功") {
            that.topTips("状态改变成功","success")
           that.tableData[index].status = status;      
          } else {
            that.topTips("状态改变失败","error")
          }
        });
    },
    exports() {//导出
      require.ensure([], () => {
        const { export_json_to_excel } = require("@/util/Export2Excel");
        const tHeader = ["优惠券ID", "名称", "介绍", "类型",  "最低消费",  "减免金额", "每人限领", "优惠券数量", "剩余数量", "状态", "使用类目"];
        const filterVal = [ "id", "title", "description",  "type", "min", "discount", "limit", "total", "surplus", "status",  "categoryTitle" ];
        const list = this.tableData;
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, "优惠券信息");
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    },
    wheel(e) {
      //滚动事件
      e = e || window.event;
      if (e.wheelDelta) {
        if (e.wheelDelta < 0) {
          //控制滚动的方向
          //向下
          this.$refs.roleRoll.wrap.scrollTop += 20;
        } else {
          this.$refs.roleRoll.wrap.scrollTop -= 20;
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
@media (max-width: 1200px) {
    .el-header {
      height: 100px!important;
    }
}
#promotion-coupon {
  //内容填满
  height: 100%;
}
.el-main {
  line-height: 0px !important;
}
.concer-input {
  //查询文本框
  width: 25%;
  margin-right: 10px;
}
.el-header {
  //查询布局
  line-height: 52px;
  height: auto !important;
}
.demo-form-inline {
  //查询布局
  white-space: pre-line;
}
.demo-form-inline > div {
  //查询布局
  margin-bottom: 0px;
}
</style>

<style>
.el-dialog__header,
.dialog-footer,
.el-tree-node__label,
.el-dialog__footer,
.el-checkbox,
.custom-tree-node {
  /*对话框的行高*/
  line-height: 0px;
}
.cell {
  /*列表居中*/
  text-align: center;
}
::-webkit-scrollbar {
  /*对话框的隐藏滚动条但是可以滚动，滚动条的宽度*/
  width: 0px !important;
}
.timevalue .el-form-item__content{
   display: flex;
}
.timevalue .el-radio-group{
   display: flex;
}
</style>
